library(tidyverse)

Map

While plotly has map plotting feature, we will use a more popular map library leaflet.

library(leaflet)
leaflet() %>% setView(lng = -121.7405, lat = 38.5449, zoom = 13) %>% 
  addTiles()
quakes %>% 
  filter(mag > quantile(mag, 0.95)) %>% 
  leaflet() %>%
  addProviderTiles(providers$Wikimedia) %>% 
  addMarkers(~long, ~lat, label = ~mag)

Choropleths

To draw a choropleth, we first need the map data. There is a package tigris to download us map data from census.

library(leaflet)
library(tigris)
states <- states(cb = TRUE)  # lowest resolution us map
class(states)
starbucks <- read_csv("starbucks.csv")
(starbucks <- starbucks %>%
  count(Province) %>%
  rename(state = Province, total = n))
## # A tibble: 54 x 2
##    state total
##    <chr> <int>
##  1 AK       42
##  2 AL       65
##  3 AR       37
##  4 AZ      391
##  5 CA     2456
##  6 CO      421
##  7 CT       97
##  8 DC       83
##  9 DE       17
## 10 FL      567
## # … with 44 more rows
states_starbucks <- states %>% 
  geo_join(starbucks, "STUSPS", "state") %>%
  subset(!is.na(total))
pal <- colorNumeric("Greens", domain=states_starbucks$total)
states_starbucks %>%
  leaflet() %>%
  setView(lng = -100, lat = 40, zoom = 4) %>% 
  addProviderTiles(providers$Wikimedia) %>% 
  addPolygons(fillColor = ~pal(total), fillOpacity = 0.7, weight = 1, smoothFactor = 0.2) %>% 
  addLegend(pal = pal, values = states_starbucks$total, position = "bottomright", title = "Starbucks")